package com.wpp.concurrent.util.countdownlatchdemo;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

public class CountDownLatchClient {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(4);
        for (int i = 0; i < 5; i++) {
            new MyThread("线程" + (i + 1), latch).start();
        }
        // main线程等待
        latch.await();
        System.out.println("main线程执行结束");

        /*List<Callable<String>> collect = Arrays.asList("aaa", "bbb", "ccc").stream().map(str -> new Callable<String>() {
            @Override
            public String call() throws Exception {
                return null;
            }
        }).collect(Collectors.toList());*/

    }
}

class MyThread extends Thread {
    private final CountDownLatch latch;
    private final Random random = new Random();

    public MyThread(String name, CountDownLatch latch) {
        super(name);
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(random.nextInt(2000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " - 执行完毕");
        // latch计数减一
        latch.countDown();
    }
}
